package com.doge.calcalbum.business.share

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.doge.calcalbum.R
import com.doge.calcalbum.analysis.analysisEvent
import com.doge.calcalbum.analysis.app_shared
import com.doge.calcalbum.core.isSharingApp
import com.doge.calcalbum.utils.appContext
import com.doge.calcalbum.utils.closeQuietly
import com.doge.calcalbum.utils.getString
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.io.ByteArrayOutputStream

object ShareHelper {
    private const val wxAppId = "wx62748230e1d7b8f4"
    fun shareApp() {
        val url = "http://www.inspace.vip/"
        val title = getString(R.string.skin_bxx)
        val description = getString(R.string.share_desc)
        wx(url, title, description)
    }

    private fun wx(
        url: String,
        title: String,
        description: String,
    ) {
        val bitmap = BitmapFactory.decodeResource(appContext.resources, R.mipmap.skin_bxx)
        val thumb = Bitmap.createScaledBitmap(bitmap, 100, 100, true)

        val wxImageObject = WXWebpageObject()
        wxImageObject.webpageUrl = url
        val msg = WXMediaMessage(wxImageObject)

        msg.title = title
        msg.description = description
        msg.thumbData = bmpToByteArray(thumb)
        val req = SendMessageToWX.Req()
        req.transaction = "img_${System.currentTimeMillis()}"
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession

        val wxAPI = WXAPIFactory.createWXAPI(appContext, wxAppId)
        wxAPI.sendReq(req)
        analysisEvent(app_shared)
        isSharingApp = true
    }


    private fun bmpToByteArray(bmp: Bitmap): ByteArray {
        val output = ByteArrayOutputStream()
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output)
        val result: ByteArray = output.toByteArray()
        closeQuietly(output)
        return result
    }
}